package com.deyou.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.activity.HouseResourceDetailActivity;
import com.deyou.activity.LoginActivity;
import com.deyou.adapter.CollectAdapter;
import com.deyou.base.BaseFragment;
import com.deyou.callback.ServerApi;
import com.deyou.event.LoginEvent;
import com.deyou.model.CollectionBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class WishListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_collect_notify)
    TextView tvCollectNotify;
    @BindView(R.id.btn_to_collect)
    TextView btnToCollect;
    @BindView(R.id.no_collection_layout)
    LinearLayout noCollectionLayout;

    private Context mContext;
    Unbinder unbinder;
    CollectAdapter mAdapter;
    private List<CollectionBean> collectionList = new ArrayList<>();
    private int page = 1;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;

    CollectAdapter.OnCollectItemClickListener collectItemClickListener = new CollectAdapter.OnCollectItemClickListener() {
        @Override
        public void collectItemClick(CollectionBean item) {
            if (!TextUtils.isEmpty(item.collectionId)){
                dealCollection(item.collectionId);
            }
        }
    };

    public WishListFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static WishListFragment newInstance(String param1, String param2) {
        WishListFragment fragment = new WishListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        this.mContext = context;
        EventBus.getDefault().register(this);
        super.onAttach(context);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wish_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        ivLeftBack.setVisibility(View.INVISIBLE);
        tvMidTitle.setText("收藏");

        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mAdapter = new CollectAdapter(mContext);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setCollectItemClick(collectItemClickListener);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(SPUtils.getStringByKey(mContext, Constants.UserId))) {
            refreshLayout.setVisibility(View.VISIBLE);
            noCollectionLayout.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            getMyCollection();
        } else {
            refreshLayout.setVisibility(View.GONE);
            noCollectionLayout.setVisibility(View.VISIBLE);
            tvCollectNotify.setText("您还没有登录");
            btnToCollect.setText("去登录");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void getMyCollection() {
        JSONObject object = new JSONObject();
        try {
            object.put("userId", SPUtils.getStringByKey(getActivity(), Constants.UserId));
            object.put("page", page);
            object.put("size", Constants.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramJson = object.toString();

        Type type = new TypeToken<LzyResponse<List<CollectionBean>>>() {}.getType();
        ServerApi.<LzyResponse<List<CollectionBean>>>getData(type, Urls.getMyCollection, "", AESUtil.encrypt(paramJson))//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        if (isRefresh || isLoadMore){

                        } else {
                            showLoading("获取收藏列表");
                        }
                    }
                })//
                .map(new Function<LzyResponse<List<CollectionBean>>, List<CollectionBean>>() {
                    @Override
                    public List<CollectionBean> apply(@NonNull LzyResponse<List<CollectionBean>> response) throws Exception {
                        return response.data;
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Observer<List<CollectionBean>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull List<CollectionBean> collectionBean) {
                        if(null != collectionBean && collectionBean.size() > 0){
                            if (!isLoadMore) {
                                dismissLoading();
                                setRefreshing(false);
                                mAdapter.setNewData(collectionBean);
                            } else {
                                mAdapter.addData(collectionBean);
                                mAdapter.loadMoreComplete();
                                if (collectionBean.size() < 20)
                                    mAdapter.loadMoreEnd(true);
                                else
                                    mAdapter.loadMoreEnd(false);
                            }
                        } else {
                            if (isLoadMore){
                                mAdapter.loadMoreComplete();
                            } else {
                                dismissLoading();
                                setRefreshing(false);
                            }
                            handler.sendEmptyMessage(1);
                        }
                        recyclerView.setAdapter(mAdapter);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                        Toast.makeText(mContext, "收藏列表获取失败", Toast.LENGTH_SHORT).show();
                        if (isLoadMore){
                            mAdapter.loadMoreComplete();
                        } else {
                            dismissLoading();
                            setRefreshing(false);
                        }
                        handler.sendEmptyMessage(1);
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        getMyCollection();
    }

    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        getMyCollection();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        AndroidUtils.startNextActivity(getActivity(), HouseResourceDetailActivity.class, null, false);
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispose();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.btn_to_collect)
    public void onViewClicked() {
        if (!TextUtils.isEmpty(SPUtils.getStringByKey(mContext, Constants.UserId))){

        } else {
            AndroidUtils.startNextActivity(getActivity(), LoginActivity.class, null ,false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(LoginEvent event) {
        if (event.isLogin()) {
            refreshLayout.setVisibility(View.VISIBLE);
            noCollectionLayout.setVisibility(View.GONE);
            getMyCollection();
        } else {
            refreshLayout.setVisibility(View.GONE);
            noCollectionLayout.setVisibility(View.VISIBLE);
            tvCollectNotify.setText("您还没有登录");
            btnToCollect.setText("去登录");
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: // 没有数据
                    if (page == 1){
                        refreshLayout.setVisibility(View.GONE);
                        noCollectionLayout.setVisibility(View.VISIBLE);
                        tvCollectNotify.setText("把您的收藏放在这里");
                        btnToCollect.setText("去添加");
                    } else {
                        refreshLayout.setVisibility(View.VISIBLE);
                        noCollectionLayout.setVisibility(View.GONE);
                    }
                    break;
                case 2:
                    break;

            }
        }
    };

    private void dealCollection(String collectionId) {
        JSONObject object = new JSONObject();
        try {
                object.put("collectionId", collectionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String paramJson = object.toString();
        ServerApi.getString(Urls.deleteCollection, "", AESUtil.encrypt(paramJson))//
                .subscribeOn(Schedulers.io())//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        showLoading("取消收藏请求中...");
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())  //
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                        if (null != resp && resp.code == 1) {
                            Toast.makeText(mContext, "取消收藏成功", Toast.LENGTH_SHORT).show();
                            onRefresh();
                        } else {
                            Toast.makeText(mContext, "取消收藏失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                        dismissLoading();
                        Toast.makeText(mContext, "取消收藏失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }
}
